﻿using MongoDB.Driver;
using Newtonsoft.Json;
using Sustainalytics.Auth.Claims;
using Sustainalytics.ClientDW.Entities.Universes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Sustainalytics.Auth.Service.GA
{
    public class UniversesClaimProvider
    {
        private readonly IMongoCollection<FeatureUniverse> _featureUniverseCollection;

        public UniversesClaimProvider(IMongoCollection<FeatureUniverse> featureUniverseCollection)
        {
            _featureUniverseCollection = featureUniverseCollection;
        }

        public async Task<Claim> GetClaimAsync(Guid accountId)
        {
            var featureUniverses = await _featureUniverseCollection
                .Find(x => x.AccountId == accountId)
                .Project(x => new { x.Feature, x.UniverseIds })
                .ToListAsync();

            var universeIdsByFeature = featureUniverses.ToDictionary(x => x.Feature, x => x.UniverseIds);
            var universesClaimValue = JsonConvert.SerializeObject(universeIdsByFeature);
            return new Claim(CustomClaimTypes.Universes, universesClaimValue);
        }
    }
}
